package com.bnlr.lrparking.appui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.appoint.MyAppointActivity;
import com.bnlr.lrparking.appui.approve.ApproveActivity;
import com.bnlr.lrparking.appui.approve.ApproveSuccessActivity;
import com.bnlr.lrparking.appui.bank.BankCardActivity;
import com.bnlr.lrparking.appui.carport.purpose.MyPurposeActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.appui.mine.collection.MyCollectActivity;
import com.bnlr.lrparking.appui.mine.recentparkrecord.RecentParkRecordActivity;
import com.bnlr.lrparking.appui.mine.mycar.MyCarActivity;
import com.bnlr.lrparking.appui.mine.mygnd.MyGNDLockAct;
import com.bnlr.lrparking.appui.mine.personal.PersonInfoActivity;
import com.bnlr.lrparking.appui.mine.record.RecordActivity;
import com.bnlr.lrparking.appui.mine.setting.SettingActivity;
import com.bnlr.lrparking.appui.mine.vip.VipTypeActivity;
import com.bnlr.lrparking.appui.publish.MyPublishActivity;
import com.bnlr.lrparking.appui.sharevalue.ShareActivity;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.UpdateUserInfoEvent;
import com.bnlr.lrparking.model.ApproveMessageM;
import com.bnlr.lrparking.model.UnPaidResponse;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.bumptech.glide.Glide;
import com.gjiazhe.panoramaimageview.GyroscopeObserver;
import com.gjiazhe.panoramaimageview.PanoramaImageView;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * @author hp
 * @date 2017/8/14
 * 个人中心
 */

public class MeFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.carport_record_red_dot)
    ImageView carportRecordRedDot;

    Unbinder unbinder;
    private View mview;
    private RelativeLayout me_chewei, me_cheliang, me_share, me_mvp_type, me_card, me_record, me_collection, me_appoint, me_head_portrait, rely_setting, me_top, me_gndlock;
    private RelativeLayout myLatestParkRecord;
    private ImageView img_head_portrait, imageView38, imageView8, imageView9, imageView10, imageView41;
    private ImageView img_approve;
    private TextView me_name;
    private String isRealNameAuth = "";
    private ApproveMessageM.DataBean amd;
    private GyroscopeObserver gyroscopeObserver;
    private PanoramaImageView panoramaImageView;
    private RelativeLayout relySunBg, me_purpose;
    private FrameLayout image_sun;
    Animation alphaAnimation;
    Boolean Lighter = false;
    Timer timer;
    MyTask myTask;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mview = inflater.inflate(R.layout.fragment_me, container, false);

        unbinder = ButterKnife.bind(this, mview);

        initView();
        // 获取用户是否有未完成的停车订单
        getIsHaveUnPaid();

        return mview;
    }

    @Override
    public void onResume() {
        super.onResume();

        // 获取用户是否有未完成的停车订单
        getIsHaveUnPaid();

        if (myTask != null) {
            myTask.cancel();
            myTask = new MyTask();
            timer.scheduleAtFixedRate(myTask, 1, 3000);
        }
        gyroscopeObserver.register(getActivity());
        if (AppConfig.getInstance().getBoolean("isLogin", false)) {
            Glide.with(getActivity())
                    .load(AppConfig.getInstance().getString("photo", ""))
                    .error(R.mipmap.personal_head)
                    .bitmapTransform(new CropCircleTransformation(getActivity()))
                    .into(img_head_portrait);
            me_name.setText(AppConfig.getInstance().getString("nickName", ""));
            imageView41.setVisibility(View.VISIBLE);
            //请求
            resultApprove();
        } else {
            me_name.setText("未登录");
            Glide.with(getActivity())
                    .load(R.mipmap.personal_head)
                    .bitmapTransform(new CropCircleTransformation(getActivity()))
                    .into(img_head_portrait);
            img_approve.setImageResource(R.mipmap.me_unrealname);
            imageView41.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 初始化页面
     */
    private void initView() {
        // 注册event bus
        EventBus.getDefault().register(this);

        gyroscopeObserver = new GyroscopeObserver();
        long time = System.currentTimeMillis();
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);

        panoramaImageView = (PanoramaImageView) mview.findViewById(R.id.me_top_bg);
        image_sun = (FrameLayout) mview.findViewById(R.id.image_sun);
        relySunBg = (RelativeLayout) mview.findViewById(R.id.rely_green);
        me_purpose = (RelativeLayout) mview.findViewById(R.id.me_purpose);
        me_purpose.setOnClickListener(this);
        imageView41 = (ImageView) mview.findViewById(R.id.imageView41);

        // 设置模式
        if (7 < mHour && mHour < 18) {
            // 日间模式
            relySunBg.setBackgroundResource(R.mipmap.sun_bg);
            image_sun.setBackgroundResource(R.mipmap.sun);
            panoramaImageView.setImageResource(R.mipmap.me_top_bg);
            panoramaImageView.setGyroscopeObserver(gyroscopeObserver);
            alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
            alphaAnimation.setDuration(3000);
            relySunBg.setAnimation(alphaAnimation);
            alphaAnimation.startNow();
        } else {                   // 夜间模式
            relySunBg.setBackgroundResource(R.mipmap.moon_bg);
            image_sun.setBackgroundResource(R.mipmap.moon);
            panoramaImageView.setImageResource(R.mipmap.me_nightbg);
            panoramaImageView.setGyroscopeObserver(gyroscopeObserver);
            alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
            alphaAnimation.setDuration(3000);
            relySunBg.setAnimation(alphaAnimation);
            alphaAnimation.startNow();
        }
        me_name = (TextView) mview.findViewById(R.id.me_name);
        me_head_portrait = (RelativeLayout) mview.findViewById(R.id.me_head_portrait);
        me_top = (RelativeLayout) mview.findViewById(R.id.me_top);
        img_head_portrait = (ImageView) mview.findViewById(R.id.img_head_portrait);
        imageView38 = (ImageView) mview.findViewById(R.id.imageView38);
        jump(imageView38, -280, 2200);
        imageView8 = (ImageView) mview.findViewById(R.id.imageView8);
        jump(imageView8, -280, 2300);
        imageView9 = (ImageView) mview.findViewById(R.id.imageView9);
        jump(imageView9, -280, 2200);
        imageView10 = (ImageView) mview.findViewById(R.id.imageView10);
        jump(imageView10, -280, 2300);
        rely_setting = (RelativeLayout) mview.findViewById(R.id.rely_setting);
        me_chewei = (RelativeLayout) mview.findViewById(R.id.me_chewei);
        me_cheliang = (RelativeLayout) mview.findViewById(R.id.me_cheliang);
        me_share = (RelativeLayout) mview.findViewById(R.id.me_share);
        me_mvp_type = (RelativeLayout) mview.findViewById(R.id.me_mvp_type);
        me_card = (RelativeLayout) mview.findViewById(R.id.me_card);
        me_record = (RelativeLayout) mview.findViewById(R.id.me_record);
        me_collection = (RelativeLayout) mview.findViewById(R.id.me_collection);
        img_approve = (ImageView) mview.findViewById(R.id.img_approve);
        me_appoint = (RelativeLayout) mview.findViewById(R.id.me_appoint);
        me_gndlock = (RelativeLayout) mview.findViewById(R.id.me_gndlock);
        myLatestParkRecord = (RelativeLayout) mview.findViewById(R.id.me_parking_record);
        myLatestParkRecord.setOnClickListener(this);
        me_gndlock.setOnClickListener(this);
        me_appoint.setOnClickListener(this);
        me_chewei.setOnClickListener(this);
        me_cheliang.setOnClickListener(this);
        rely_setting.setOnClickListener(this);
        me_share.setOnClickListener(this);
        me_mvp_type.setOnClickListener(this);
        me_card.setOnClickListener(this);
        me_record.setOnClickListener(this);
        me_collection.setOnClickListener(this);
        img_approve.setOnClickListener(this);
        me_top.setOnClickListener(this);

        timer = new Timer();
        myTask = new MyTask();
    }

    /**
     * 跳跃动画
     *
     * @param image 控件
     * @param num   距离
     * @param l     持续时间
     */
    private void jump(ImageView image, float num, long l) {
        //位移动画，从button的上方300像素位置开始
        TranslateAnimation down = new TranslateAnimation(0, 0, num, 0);
        down.setFillAfter(true);
        down.setInterpolator(new BounceInterpolator());
        down.setDuration(l);
        image.startAnimation(down);
    }

    @Override
    public void onClick(View view) {
        // 检查登录状态
        if (!AppConfig.getInstance().getBoolean("isLogin", false)) {
            startActivity(new Intent(getActivity(), VerificaActivity.class));
            return;
        }
        switch (view.getId()) {
            // 我的发布
            case R.id.me_chewei:
                startActivity(new Intent(getActivity(), MyPublishActivity.class));
                //startActivity(SelectMyPublishActivity.class);
                break;
            // 我的车辆
            case R.id.me_cheliang:
                startActivity(MyCarActivity.class);
                break;
            // 共享值
            case R.id.me_share:
                startActivity(ShareActivity.class);
                break;
            // 银行卡
            case R.id.me_card:
                startActivity(BankCardActivity.class);
                break;
            // 消费记录
            case R.id.me_record:
                //记录
                startActivity(RecordActivity.class);
                break;
            // 我的收藏
            case R.id.me_collection:
                startActivity(MyCollectActivity.class);
                break;
            // 实名认证状态
            case R.id.img_approve:
                //认证
                if (isRealNameAuth.equals("0")) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ApproveActivity.class);
                    //跳转并发送请求码
                    startActivityForResult(intent, 0);
                } else if (isRealNameAuth.equals("1") || isRealNameAuth.equals("3")) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ApproveSuccessActivity.class);
                    intent.putExtra("isRealNameAuth", amd);
                    //跳转并发送请求码
                    startActivity(intent);
                } else {
                    ToastUtils.showShort("身份信息正在审核中");
                }
                break;
            // 个人信息
            case R.id.me_top:
                startActivity(PersonInfoActivity.class);
                break;
            // 我的预约
            case R.id.me_appoint:
                startActivity(MyAppointActivity.class);
                break;
            // 租用意向
            case R.id.me_purpose:
                startActivity(MyPurposeActivity.class);
                break;
            // 会员类别
            case R.id.me_mvp_type:
                startActivity(VipTypeActivity.class);
                break;
            // 我的设置
            case R.id.rely_setting:
                startActivity(SettingActivity.class);
                break;
            // 我的地锁
            case R.id.me_gndlock:
                startActivity(MyGNDLockAct.class);
                break;
            // 最近停车记录
            case R.id.me_parking_record:
                startActivity(RecentParkRecordActivity.class);
                break;
            default:
                break;
        }
    }

    /**
     * 提交身份验证
     */
    private void resultApprove() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "GetRealNameAuthStatus");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<ApproveMessageM>(getActivity(), true, ApproveMessageM.class) {
                        @Override
                        public void doWork(ApproveMessageM data, String code) {
                            if (TextUtils.equals("1", code)) {
                                isRealNameAuth = data.getData().getIsRealNameAuth();
                                amd = data.getData();
                                AppConfig.getInstance().putString("isRealNameAuth", data.getData().getIsRealNameAuth());
                                AppConfig.getInstance().putString("realName", data.getData().getName());
                                //未认证
                                if (isRealNameAuth.equals("0")) {
                                    img_approve.setImageResource(R.mipmap.me_unrealname);
                                }
                                //已认证
                                else if (isRealNameAuth.equals("1")) {
                                    img_approve.setImageResource(R.mipmap.me_realname1);
                                }
                                //认证中
                                else if (isRealNameAuth.equals("2")) {
                                    img_approve.setImageResource(R.mipmap.me_realname_inaudit);
                                }
                                //认证失败
                                else if (isRealNameAuth.equals("3")) {
                                    img_approve.setImageResource(R.mipmap.me_realname_fail);
                                }
                            } else {
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录") ||
                                        obj.getString("msg").contains("请重新登录"))) {
                                    AppConfig.getInstance().putBoolean("isLogin", false);
                                    final CarCommon carCommon = new CarCommon();

                                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                        @Override
                                        public void setSure() {
                                            Intent intent = new Intent(getActivity(), VerificaActivity.class);
                                            getActivity().startActivity(intent);

                                        }
                                    });
                                    carCommon.ReminderDialog(getActivity(), "登录信息已过期，是否重新登录？", "下线通知", "立即登录");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    alphaAnimation.cancel();
                    alphaAnimation = new AlphaAnimation(0.3f, 1.0f);
                    alphaAnimation.setDuration(3000);
                    relySunBg.setAnimation(alphaAnimation);
                    alphaAnimation.startNow();
                    break;
                case 2:
                    alphaAnimation.cancel();
                    alphaAnimation = new AlphaAnimation(1.0f, 0.3f);
                    alphaAnimation.setDuration(3000);
                    relySunBg.setAnimation(alphaAnimation);
                    alphaAnimation.startNow();
                    break;
            }
        }

        ;
    };

    private class MyTask extends TimerTask {
        @Override
        public void run() {
            if (Lighter) {
                Lighter = false;
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
            } else {
                Lighter = true;
                Message message = new Message();
                message.what = 2;
                mHandler.sendMessage(message);
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (myTask != null) {
            myTask.cancel();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateUserInfo(UpdateUserInfoEvent event) {
        Glide.with(getActivity())
                .load(AppConfig.getInstance().getString("photo", ""))
                .error(R.mipmap.personal_head)
                .bitmapTransform(new CropCircleTransformation(getActivity()))
                .into(img_head_portrait);
        me_name.setText(AppConfig.getInstance().getString("nickName", ""));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        myTask.cancel();
        timer = null;
        myTask = null;
    }

    /**
     * 获取当前是否有未支付的订单
     * 停车记录
     */
    public void getIsHaveUnPaid() {

        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "UnPaid");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            CallServer.getRequestInstance()
                    .add(getActivity(), mRequest,
                            new CustomHttpListener<UnPaidResponse>(getActivity(), true, UnPaidResponse.class) {
                                @Override
                                public void doWork(UnPaidResponse data, String code) {
                                    LogUtils.d(data.toString());
                                    if (data.getData().isDealStatus()){
                                        carportRecordRedDot.setVisibility(View.VISIBLE);
                                    }else {
                                        carportRecordRedDot.setVisibility(View.GONE);
                                    }
                                }
                            }, false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
